import React, { useEffect, useState } from 'react'
import './knowledge.less'
import { Button, Drawer, Switch, Upload, Card, Form, Input, Pagination, Dropdown, Menu, Select, message, Popconfirm, Divider } from 'antd';
import { getKnowledgeList, deleteKnowledgeList, crateData, editData } from '@/api/knowledge'
import type { DrawerProps } from 'antd/es/drawer';
import { InboxOutlined, UploadOutlined } from '@ant-design/icons';
import { getFileList } from '@/api/file'
import axios from '@/utils/request'
import moment from 'moment'
import { history } from 'umi'
import request from '@/utils/request';
import { newActicle } from '@/utils/works';

type Props = {}

const Knowledge = (props: Props) => {
  const { Option } = Select;
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(12)
  const [page1, setPage1] = useState(1)
  const [pageSize1, setPageSize1] = useState(12)
  const [fileList, setFileList] = useState([])
  const [knowLedgeList, setKnowledgeList] = useState([])
  const [open, setOpen] = useState(false)
  const [open1, setOpen1] = useState(false)
  const [form] = Form.useForm();
  const [forms] = Form.useForm();
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const [name, setName] = useState('')
  const [isShow, setIsShow] = useState(false)
  const [size, setSize] = useState<DrawerProps['size']>();
  const [sums, setSums] = useState(0);
  const [sums1, setSums1] = useState(0);
  let [edit_value, setEdit_value] = useState('') as newActicle
  let [searchIMG, setSearchIMG] = useState<newActicle>({})
  let [setIMG, IMGE] = useState({}) as newActicle


  useEffect(() => {
    setSize('large'),
      (
        async () => {
          //知识小册数据
          let res = await getKnowledgeList(page, pageSize)
          console.log(res);

          setKnowledgeList(res.data.data[0])
          setSums(res.data.data[1])

          //文件数据
          let res1 = await getFileList(page1, pageSize1)
          setFileList(res1.data.data[0])
          setSums1(res1.data.data[1])
        }


      )()

  }, [])

  //搜索
  const onFinish = async (values: newActicle) => {
    console.log(values);
    let res = await getKnowledgeList(page, pageSize, values.title, values.status)
    setKnowledgeList(res.data.data[0])
    setSums(res.data.data[1])
  };

  const onFinishFailed = (errorInfo: newActicle) => {
    console.log('Failed:', errorInfo);
  };

  //删除
  const confirm = async (item: newActicle) => {
    await deleteKnowledgeList(item.id, {
      title: item.title,
      summary: item.summary
    })
    let res = await getKnowledgeList(page, pageSize)
    setKnowledgeList(res.data.data[0])
    message.success('删除成功');
  };

  //新建知识库弹窗显示
  const showDrawer = (type: string, item: newActicle) => {
    if (type === 'create') {
      setName('新建知识库')
      setIsShow(true);
      //重置表单
      form.resetFields();
    } else {
      setName('更新知识库')
      setIsShow(false)
      form.setFieldsValue(item);
    }

    setOpen(true);


  };
  //弹窗关闭
  const onClose = () => {
    setOpen(false);
  };


  //上传文件
  const normFile = (e: newActicle) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const normFile1 = (e: newActicle) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };


  //新建完成
  const finishCreate = async (values: newActicle) => {
    await crateData({
      title: values.title,
      summary: values.summary
    })
    let res = await getKnowledgeList(page, pageSize)
    setKnowledgeList(res.data.data[0])
    onClose()
    location.reload()



  }

  //编辑
  const finishEdit = async (values: newActicle) => {
    let id = ''
    knowLedgeList.forEach((item: newActicle, index: number) => {
      if (item.title === values.title || item.summary === values.summary) {
        id = item.id
      }
    })

    console.log(id);

    await editData(id, {
      title: values.title,
      summary: values.summary
    })

    let res = await getKnowledgeList(page, pageSize)
    setKnowledgeList(res.data.data[0])
    onClose()
  }


  //搜索文件
  const searchFile = async (values: newActicle) => {
    let res = await getFileList(page1, pageSize1, values.originalname, values.type)
    setFileList(res.data.data[0])
    setSums1(res.data.data[1])

  }

  //oss上传
  const handleUpload = (e: newActicle) => {
    console.log(e.target)
    const { files } = e.target
    let formDate = new FormData()
    formDate.append('file', files[0])
    axios.defaults.headers.post['Authorization'] = `Bearer ${localStorage.getItem('token')}`
    axios({
      url: "/api/file/upload?unique=0",
      method: 'post',
      data: formDate,
    }).then(async (res) => {
      message.success('上传成功');
      IMGE(res.data.data)
      console.log(res)
      console.log(setIMG);
      await axios.get(`https://2002b-oss.oss-cn-hangzhou.aliyuncs.com/${moment(new Date()).format('YYYY-MM-DD')}/${res.data.data.originalname}`);
    })
  }

  const goDetail = (item: newActicle) => {
    history.push({ pathname: `/DetailKnowledge/${item.id}`, query: item })
  }

  const menu = (
    <Menu
      items={[
        {
          key: '1',
          label: (
            <a className='fb' target="_blank" rel="noopener noreferrer" >
              发布线上
            </a>
          ),
        },

      ]}
    />
  )
  const menu1 = (
    <Menu
      items={[
        {
          key: '1',
          label: (
            <a className='fb' target="_blank" rel="noopener noreferrer" >
              设为草稿
            </a>
          ),
        },

      ]}
    />
  )

  return (
    <div className='knowledge'>
      <div className="top">

        <Form
          form={forms}
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <div className="topCon">
            <Form.Item
              className='topItem'
              label="名称"
              name="title"
            >
              <Input placeholder='请输入知识库名称' />
            </Form.Item>

            <Form.Item
              className='topItem'
              label="状态"
              name="status"

            >
              <Select
                style={{ width: 180 }}
                // onChange={onGenderChange}
                allowClear
              >
                <Option value="publish">已发布</Option>
                <Option value="11111">草稿</Option>


              </Select>
            </Form.Item>
          </div>
          <Form.Item className='knowBtns'>
            <Button className='bt' type="primary" htmlType="submit">
              搜索
              </Button>
            <Button onClick={() => forms.resetFields()} >
              重置
              </Button>
          </Form.Item>




        </Form>



      </div>
      <div className="con1">
        <div className='newBtn'> <Button onClick={() => showDrawer('create', "")} type="primary">+新建</Button></div>
        <div className="know">
          {
            knowLedgeList.length > 0 ? knowLedgeList.map((item: newActicle, index: number) => {
              return <div className="knowbox" key={index}>

                <div className="maincon">
                  <div className="tcon">
                    <img src={item.cover} alt="" />
                    <span>{item.title}</span>
                  </div>
                  <p>{item.title}</p>
                  <li>{item.summary}</li>

                </div>
                <div className='tags'>
                  <span
                    onClick={() => goDetail(item)}
                  ><svg className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2179" width="19" height="19"><path d="M960 960H64v-64h896v64z m-73.6-686.4l-84 84-45.6 45.6L384 776l-192 56 56-192 502.4-502.4c4-4 9.6-6.4 14.4-6.4 4 0 8 1.6 10.4 4L888 248c7.2 7.2 5.6 17.6-1.6 25.6zM712 357.6L666.4 312 304.8 673.6l-18.4 64 64-18.4L712 357.6z m97.6-97.6l-45.6-45.6-52 52 45.6 45.6 52-52z" p-id="2180" fill="#2c2c2c"></path></svg></span> <b>|</b>
                  <span
                    onClick={() => {
                      if (item.status === "publish") {
                        request.patch(`http://111.67.198.176:8103/api/knowledge/${item.id}`, {
                          status: "draft"
                        }).then(res => {
                          console.log(res);
                          message.success("下线成功")
                          window.location.reload()
                          // setFileList(res.data.data)
                        })
                      } else {
                        request.patch(`http://111.67.198.176:8103/api/knowledge/${item.id}`, {
                          status: "publish"
                        }).then(res => {
                          console.log(res);
                          message.success("上线成功")
                          window.location.reload()
                          // setFileList(res.data.data)
                        })
                      }
                    }}
                  >
                    {
                      item.status === "publish" ?
                        <Dropdown overlay={menu1} placement="top" arrow>
                          <svg className="icon" viewBox="0 0 1382 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5354" width="16" height="16"><path d="M1098.720126 393.238707A429.040555 429.040555 0 0 0 665.583719 0.036863a434.16037 434.16037 0 0 0-430.064517 393.201844A272.886176 272.886176 0 0 0 0.00768 665.612902a278.005992 278.005992 0 0 0 274.422121 274.934102h39.422581v-76.285253h-39.422581a197.112904 197.112904 0 0 1-23.551152-392.689864l62.973733-7.679723V400.918431a354.803227 354.803227 0 0 1 706.022583 0l8.191705 62.973733 54.782028 7.679723A204.792627 204.792627 0 0 1 1255.386486 665.612902a194.041015 194.041015 0 0 1-196.08894 196.600922h-39.422581v78.33318h39.422581a276.470047 276.470047 0 0 0 39.42258-549.356223z" p-id="5355"></path><path d="M949.221508 746.50599l-54.782028-54.782028-188.409217 187.897236V314.905527h-78.33318v557.035947l-180.217512-180.217512-55.294009 54.782028 274.934102 274.422121 282.101844-274.422121z" p-id="5356"></path></svg>
                        </Dropdown>
                        : <Dropdown overlay={menu} placement="top" arrow>
                          <svg className="icon" viewBox="0 0 1024 1024" version=" 1.1" xmlns="http://www.w3.org/2000/svg" p-id="12732" width="19" height="19"><path d="M717.04381 783.847619h-70.095239v-48.761905h70.095239a161.158095 161.158095 0 1 0 0-322.31619H696.07619l-3.291428-20.72381a168.472381 168.472381 0 0 0-333.04381 0l-3.047619 20.72381h-31.573333a161.158095 161.158095 0 0 0 0 322.31619h74.971429v48.761905h-74.971429a209.92 209.92 0 0 1-9.386667-419.718095 217.112381 217.112381 0 0 1 421.302857 0.731428 209.92 209.92 0 0 1-19.99238 418.986667z" fill="#2c2c2c" p-id="12733"></path><path d="M504.56381 561.005714h48.761904v227.108572h-48.761904z" fill="#2c2c2c" p-id="12734"></path><path d="M462.262857 648.899048l-34.499047-34.499048 101.180952-101.180952 101.302857 101.180952-34.499048 34.499048-66.803809-66.681905-66.681905 66.681905z" fill="#2c2c2c" p-id="12735"></path></svg>
                        </Dropdown>
                    }
                  </span><b>|</b>
                  <span onClick={() => showDrawer('edit', item)}><svg className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="13793" width="19" height="19"><path d="M512 305.318124a205.708492 205.708492 0 1 0 205.708492 205.708492 205.708492 205.708492 0 0 0-205.708492-205.708492z m0 346.200254a140.816223 140.816223 0 1 1 140.816223-140.816223 140.816223 140.816223 0 0 1-140.816223 141.140684z" fill="#2c2c2c" p-id="13794"></path><path d="M958.78327 393.57161l-73.003802-11.031686a391.949303 391.949303 0 0 0-16.87199-40.882129l44.126743-60.025349a64.892269 64.892269 0 0 0 0-91.82256l-77.2218-77.870723a64.892269 64.892269 0 0 0-91.82256 0L684.937896 155.741445a392.273764 392.273764 0 0 0-40.882129-17.196451L632.69962 64.892269a64.892269 64.892269 0 0 0-64.892269-64.892269h-109.343473a64.892269 64.892269 0 0 0-64.892268 64.892269l-11.031686 72.679341a392.598226 392.598226 0 0 0-40.882129 16.871989L281.307985 110.316857a64.892269 64.892269 0 0 0-91.82256 0L111.939163 187.863118a64.892269 64.892269 0 0 0 0 91.82256l44.126743 60.025349a392.273764 392.273764 0 0 0-16.547528 39.908745L64.892269 389.353612a64.892269 64.892269 0 0 0-64.892269 64.892269v109.667934a64.892269 64.892269 0 0 0 64.892269 64.892269l74.301647 11.356147a392.273764 392.273764 0 0 0 16.223068 41.20659L110.316857 742.367554a64.892269 64.892269 0 0 0 0 91.82256l77.546261 77.546261a64.892269 64.892269 0 0 0 91.82256 0l60.674271-44.775665a392.598226 392.598226 0 0 0 39.259823 16.547528l11.356147 75.599493a64.892269 64.892269 0 0 0 64.892269 64.892269h109.667934a64.892269 64.892269 0 0 0 64.892268-64.892269l11.356147-74.301647a392.922687 392.922687 0 0 0 39.584284-16.223068l61.323194 45.100127a64.892269 64.892269 0 0 0 91.82256 0l77.546262-77.546261a64.892269 64.892269 0 0 0 0-91.82256l-44.126743-60.025349a392.273764 392.273764 0 0 0 16.87199-39.908745l74.626109-11.356147a64.892269 64.892269 0 0 0 64.892268-64.892269v-109.667934a64.892269 64.892269 0 0 0-65.541191-64.892268z m0 174.560202h-9.73384l-74.626109 11.356147-38.286439 5.840305-12.978454 36.33967a329.328264 329.328264 0 0 1-13.951837 32.446134l-17.196452 35.366287 23.361217 32.446134 44.126743 60.025349 2.920152 3.893536 3.569075 3.569075-77.546261 78.195183-3.569075-3.569074-3.893536-2.920152-61.323194-45.100127-32.446135-23.036756-33.743979 18.169836a329.652725 329.652725 0 0 1-32.446135 13.627376l-36.988593 12.978454-6.489227 38.286438-11.356147 74.301648v9.73384h-110.316856V949.04943l-11.356147-75.599493-5.840305-38.286439-36.664131-12.978454a329.003802 329.003802 0 0 1-32.446135-13.627376l-35.366286-16.87199-32.446135 23.036755-60.674271 44.775666-3.893536 2.920152-3.569075 3.569075-77.546261-77.546261 3.569075-3.569075 2.595691-3.893536 45.424588-61.323194 23.036755-32.446135-16.87199-35.041825a329.328264 329.328264 0 0 1-13.627376-32.446134L187.538657 584.030418l-38.6109-6.489227-74.301648-11.356147H64.892269V454.245881h9.73384l74.626109-11.356147 38.6109-5.840304 12.978454-36.664132a329.328264 329.328264 0 0 1 13.951837-32.446135l16.87199-35.041825-23.036755-32.446134-44.451204-59.376426L162.230672 237.181242l-4.217998-3.569075 77.2218-77.546261 3.569075 3.569075 3.893536 2.595691 60.34981 44.775665 32.446134 23.036756 35.041825-16.87199a329.003802 329.003802 0 0 1 34.068441-14.276299l36.988593-12.978454 5.840305-38.6109 10.058301-72.679341V64.892269h110.316857v9.73384l11.356147 73.652725 4.86692 38.286438 36.664132 12.978454a329.003802 329.003802 0 0 1 34.392902 14.276299l35.366287 17.196452 32.446134-23.361217 59.376426-43.47782 4.217998-1.946768 3.569074-3.569075 77.546261 77.546261-3.569074 3.569075-2.920152 3.893536-44.451204 59.376426-23.036756 32.446134 17.520913 33.74398a328.679341 328.679341 0 0 1 13.951837 34.068441l12.653993 36.988593 38.935361 5.840304 73.003802 11.031686h9.733841z" fill="#2c2c2c" p-id="13795"></path></svg></span><b>|</b>

                  <span>
                    <Popconfirm
                      title="确定要删除这条数据吗?"
                      onConfirm={() => confirm(item)}
                      okText="Yes"
                      cancelText="No"
                    > <svg className="icon" viewBox="0 0 1024 1024"
                      version="1.1" xmlns="http://www.w3.org/2000/svg"
                      p-id="18798" width="19" height="19">
                        <path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 
                    8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 
                    64v80h72v-72zM864 256H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l
                    24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H88
                    8c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24
                    .2 512z" p-id="18799" fill="#2c2c2c"></path></svg>
                    </Popconfirm>
                  </span>

                </div>
              </div>
            }) : <div className='nulldata'>
              暂无数据
            </div>
          }
        </div>

        <div className="page">

          <Pagination
            showTotal={total => `共 ${sums} 条`}
            defaultCurrent={1}
            total={sums}
            defaultPageSize={12}
            pageSizeOptions={[8, 12, 24, 36]}
            showLessItems
            showSizeChanger
            onChange={async (a, b) => {
              console.log(a, b)
              let res = await getKnowledgeList(a, b)
              setKnowledgeList(res.data.data[0])
              setSums(res.data.data[1])
            }}
          />
        </div>
        <Drawer size={size} title={name} placement="right" onClose={onClose} open={open}>
          {
            isShow ? <div className='create'>
              <Form
                form={form2}
                initialValues={{ remember: true }}
                onFinish={finishCreate}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
              >
                <Form.Item
                  label="名称"
                  name="title"
                >
                  <Input />
                </Form.Item>

                <Form.Item
                  label="描述"
                  name="summary"
                >
                  <Input />
                </Form.Item>
                <Form.Item name="isCommentable" label="评论" valuePropName="checked">
                  <Switch />
                </Form.Item>
                <Form.Item label="封面" valuePropName='fileList' name="url">
                  <div className="posterUplod">
                    <Form.Item name="cover">
                      <div className='UplodJPG'>
                        <InboxOutlined className='Jpgs' />
                        <img className={setIMG.url ? 'IMGs' : "imgs"} src={setIMG.url ? setIMG.url : edit_value.id ? searchIMG.cover ? searchIMG.cover : '' : ''} alt="" />
                        <input id='file' type="file" onChange={handleUpload} />
                        <p className="ant-upload-text">点击选择文件或将文件拖拽到此处</p>
                        <p className="ant-upload-hint">文件将上传到OSS,如未配置请先配置</p>
                      </div>
                    </Form.Item>
                  </div>
                </Form.Item>
                <Form.Item>
                  <Input />
                </Form.Item>

                <Form.Item>
                  <Button onClick={() => setOpen1(true)} >
                    选择文件
                  </Button>
                </Form.Item>

                <div className="btns">
                  <Button onClick={onClose} >
                    取消
                  </Button>
                  <Button htmlType="submit">
                    创建
                  </Button>
                </div>
              </Form>

            </div> :
              <div className='edit' >
                <Form
                  form={form}
                  name="basic"
                  initialValues={{ remember: true }}
                  onFinish={finishEdit}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                >
                  <Form.Item
                    label="名称"
                    name="title"
                  >

                    <Input></Input>
                  </Form.Item>

                  <Form.Item
                    label="描述"
                    name="summary"
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item name="isCommentable" label="评论" valuePropName="checked">
                    <Switch />
                  </Form.Item>
                  <Form.Item label="封面">
                    <div className="posterUplod">
                      <Form.Item name="cover">
                        <div className='UplodJPG'>
                          <InboxOutlined className='Jpgs' />
                          <img className={setIMG.url ? 'IMGs' : "imgs"} src={setIMG.url ? setIMG.url : edit_value.id ? searchIMG.cover ? searchIMG.cover : '' : ''} alt="" />
                          <input id='file' type="file" onChange={handleUpload} />
                          <p className="ant-upload-text">点击选择文件或将文件拖拽到此处</p>
                          <p className="ant-upload-hint">文件将上传到OSS,如未配置请先配置</p>
                        </div>
                      </Form.Item>
                    </div>
                  </Form.Item>
                  <Form.Item
                  >
                    <Input />
                  </Form.Item>

                  <Form.Item>
                    <Button onClick={() => setOpen1(true)} >
                      选择文件
                    </Button>
                  </Form.Item>

                  <div className="btns">
                    <Button onClick={onClose} >
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit" >
                      更新
                    </Button>
                  </div>
                </Form>

              </div>
          }
        </Drawer>

        {/* 点击选择文件出现弹窗 */}
        <Drawer className='fileWrap' size='large' title="文件选择" placement="right" onClose={() => setOpen1(false)} open={open1}>

          <Form
            form={form1}
            name="validate_other"
            onFinish={searchFile}
            autoComplete="off"
          >

            <div className="fileTop">
              <Form.Item
                className='fileItem'
                label="文件名"
                name="originalname"

              >
                <Input placeholder='请输入文件...' />
              </Form.Item>

              <Form.Item
                className='fileItem'
                label="文件类"
                name="type"
              >
                <Input placeholder='请输入文件...' />
              </Form.Item>
            </div>


            <Form.Item className='setBtn' >
              <Button className='btnItems' type="primary" htmlType="submit">
                搜索
                </Button>
              <Button className='btnItems' onClick={async () => {
                form1.resetFields()
                let res = await getFileList(page1, pageSize1)
                setFileList(res.data.data[0])

              }} >
                重置
                </Button>
            </Form.Item>

            <Form.Item
              label=""
              className='upFileItem'
              valuePropName="fileList"
              getValueFromEvent={normFile1}
              name="upload"
            >
              <Upload name="logo" action="/upload.do" listType="picture">
                <Button className='upFile'>上传文件</Button>
              </Upload>
            </Form.Item>


          </Form>

          <div className="fileCon">
            {
              fileList.length ? fileList.map((item: newActicle, index: number) => {
                return <Card
                  key={index}
                  hoverable
                  style={{ width: "23%", margin: "1%" }}
                >
                  <img src={item.url} alt="" />
                  <p>{item.originalname}</p>


                </Card>

              }) : <div className='none'>暂无数据</div>
            }

            <Pagination
              defaultCurrent={1}
              total={sums1}
              defaultPageSize={12}
              pageSizeOptions={[8, 12, 24, 36]}
              showLessItems
              showSizeChanger
              onChange={async (a, b) => {
                console.log(a, b)
                let res = await getFileList(a, b)
                setFileList(res.data.data[0])
                setSums(res.data.data[1])
              }}
              showTotal={total => `共 ${total} 条`}

            />

          </div>

        </Drawer>

      </div>


    </div>
  )
}

export default Knowledge